/*
 * @Author: TJN tjn@246@126.com
 * @Date: 2024-06-21 16:54:27
 * @LastEditors: TJN tjn@246@126.com
 * @LastEditTime: 2024-06-24 15:15:31
 * @FilePath: \hdcms-nest\src\validate\is-not-exists.ts
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
import { PrismaClient } from '@prisma/client';
import {
  registerDecorator,
  ValidationOptions,
  ValidationArguments,
} from 'class-validator';

export function IsNotExists(
  property: string,
  feilds: string[],
  validationOptions?: ValidationOptions,
) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      name: 'IsNotExists',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        async validate(value: any, args: ValidationArguments) {

          // 去表中查询有没有要注册得字段，如果表中没有就证明可以注册，如果表中存在就不让注册
          const prisma = new PrismaClient({ log: ['query'] });

          const user = await prisma[property].findFirst({
            where: {
              // OR:[
              //   {
              //     email: value,
              //   },
              //   {
              //     name: value,
              //   },
              //   {
              //     mobile: value,
              //   },
              // ]
              OR: feilds.map((field) => ({
                [field]: value,
              })),
            },
          });
          // 如果表中存在就取反，说明不能注册
          return !Boolean(user);
        },
      },
    });
  };
}
